/**
 * ajax.lookAraound.jax
 * Business Logic:
 * 		Step 01: get userId from login 
 * 		Step 02: call service to get user info based on userId
 * 		Step 03: load map with user logged in
 * 		Step 04: get list of friends when user clicks search (pagination)
 * 		Step 05: update map
 * Author: Phu
 * Date: May 28, 2014
 */

var map;
var offset = -1;
var homePosition = null;
var userId = '';
var markers = Array();
var infos = Array();
var lables = Array();
var currentTextSearch = '';

// Store list for marker and user info
var userMaker = null;
var userInfo = null;

/**
 * After Login.
 */
function afterLogin() {
	// Step 01: load map
	google.maps.event.addDomListener(window, 'resize', initMap);
	google.maps.event.addDomListener(window, 'load', initMap);

	// //Step 02: load info for the first time log in
	initMap();
}

/**
 * Load map more 
 */
function loadMore(users) {
	
	// Set the last users
	for ( var i = 0; i < users.length; i++) {
		var user = users[i];
		var avatar = getAvatar(user);
		var image = getIcon(avatar);
		var pos = getLatLng(user.located);
		var marker = new google.maps.Marker({
		     position: pos,
		     map: map,
		     icon: image,
		     title: user.username,
		     draggable: true,
		     infoWindowIndex : i+(offset*MAX_PAGE+1)
		 });
		
		var dist = distance(homePosition.lat(), homePosition.lng(), pos.lat(), pos.lng(), 'K');
	    var label = new Label({
	        map: map,
	        title: user.fullname + ' ('+ formatRound(dist) +')'
	      });
	    label.bindTo('position', marker, 'position');
	    label.bindTo('text', marker, 'position');
	    
	    var info = getPopupInfo(user);
	    
	    infoWindow = new google.maps.InfoWindow({
			content : info 
		});
		google.maps.event.addListener(marker, "click",function(e) {
							infos[this.infoWindowIndex].open(map, this);
						});
		infos.push(infoWindow);
		markers.push(marker);
		lables.push(label);
	}
}

/**
 * Update Users by meter
 */
function getUsers() {
	//load user account from cookie
	var textSearch = $('#textSearch').val();
	if (userId != '' && userId != null) {
		var urlString = "/search?action=getUsersByKm&userId=" + userId
				+ "&latitude=" + homePosition.lat() 
				+ "&longitude=" + homePosition.lng()
				+ "&distance=" + currentTextSearch 
				+ "&offset=" + offset
		$.ajax({
			url : urlString,
			type: 'GET',
	        data: '',
			success : function(resp) {
				if (resp != null) {
					// getting the data from the response object
					var data = resp.data;
					
					//initialize map
					if(data.length > 0) {
						if (offset == 0) {
							loadFirst(data);
						} else {
							loadMore(data);
						}
					}
					else {
						alert('No record found more');
						$("#searchButton").html('Go');
					}
						
				}
			},
			error : function(resp){
				alert('Cannot get data! Please check again');
				$("#searchButton").html('Go');
			}
		});
	} else {//not login
		//Go to index page
		document.location.href = '/index.html';
	}
}


/**
 * Create Map.
 * 
 */
function createMap(user) {
	
	markers = Array();
	infos = Array();
	labels = Array();
	
	//Set profile
	setProfile(user);
	
	//set map options
	var mapOptions
	if (user.located == NULL) {
		mapOptions = {
				zoom : 8,
				center : new google.maps.LatLng(40.111689,-78.134766),//new york
				mapTypeId : google.maps.MapTypeId.ROADMAP
			};
		homePosition = new google.maps.LatLng(40.111689,-78.134766);
	} else {
		homePosition = getLatLng(user.located);
		mapOptions = {
				zoom : 8,
				center : homePosition,
				mapTypeId : google.maps.MapTypeId.ROADMAP
			};
	}
	
	//load map with user's position
	map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
	
	var avatar = getAvatar(user);
	var image = getIcon(avatar);
	
	userMaker = new google.maps.Marker({
	     position: homePosition,
	     map: map,
	     icon: image,
	     title: user.username,
	     draggable: true,
//	     animation: google.maps.Animation.BOUNCE,
	     infoWindowIndex : offset
	});
	
	var label = new Label({
	    map: map,
	    title: user.fullname
	});
	label.bindTo('position', userMaker, 'position');
	label.bindTo('text', userMaker, 'position');
	
	
	var info = getPopupInfo(user);
	userInfo = new google.maps.InfoWindow({
		content : info
	});
	google.maps.event.addListener(userMaker, "click", 
			function(e) {
				userInfo.open(map, this);
			});
	
	infos.push(userInfo);
	markers.push(userMaker);
	lables.push(label);
}

function loadFirst(users) {
	//Get user login to initialize map
	markers = Array();
	infos = Array();
	
	// Set the last users
	for ( var i = 0; i < users.length; i++) {
		var user = users[i];
		var avatar = getAvatar(user);
		var image = getIcon(avatar);
		var pos = getLatLng(user.located);
		var marker = new google.maps.Marker({
		     position: pos,
		     map: map,
		     icon: image,
		     title: user.username,
		     draggable: true,
			 infoWindowIndex : i + (offset * MAX_PAGE)
		 });
		var label;
		if (user.user_id == userId) {
//			marker.setAnimation(google.maps.Animation.BOUNCE);
			label = new Label({
		        map: map,
		        title: user.fullname
		      });
		} else {
			var dist = distance(homePosition.lat(), homePosition.lng(), pos.lat(), pos.lng(), 'K');
		    label = new Label({
		        map: map,
		        title: user.fullname + ' ('+ formatRound(dist) +')'
		      });
		}

		
	    label.bindTo('position', marker, 'position');
	    label.bindTo('text', marker, 'position');
	    
	    var info = getPopupInfo(user);
	    
	    infoWindow = new google.maps.InfoWindow({
			content : info 
		});
		google.maps.event.addListener(marker, "click",function(e) {
							infos[this.infoWindowIndex].open(map, this);
						});
		infos.push(infoWindow);
		markers.push(marker);
		lables.push(label);
	}
}


/**
 * load current user logged in phonemap
 */
function getUser() {
	$.ajax({
		url : "/search?action=initMap&userId="+userId,
		type: 'GET',
        data: '',
		success : function(resp) {
			if (resp != null) {
				// getting the data from the response object
				var data = resp.data;
				//initialize map
				if(data.length > 0) {
					//load map with current user
					createMap(data[0]);
				}
			}
		},
		error : function(resp){
			alert('Cannot get data! Please check again');
		}
	});
}

/**
 * Load map
 */
function initMap() {
	offset = -1;
	userId = $.cookie('useraccount');
	if (userId != '' && userId != null) {
		//load current user with map
		getUser();
	} else {
		//Go to index page
		document.location.href = '/index.html';
	}
}

/**
 * Go home's position
 */
function goHome() {
	map.panTo(homePosition);
}

//Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
  if (markers) {
    for (i in markers) {
    	markers[i].setMap(null);
    	lables[i].onRemove();
    }
    markers = new Array();
    infos = new Array();
    lables = new Array();
  }
}	
	
/**
 * Do Search.
 */
function doSearch() {
	var searchButton = $("#searchButton").html();
	if ($('#textSearch').val() != null && $('#textSearch').val() != '') {
		if (searchButton === 'Go') {
			offset = 0;
			currentTextSearch = $('#textSearch').val();
			$("#searchButton").html('More');
			clearOverlays();
			
		} else {
			offset = offset + 1;
		}
		getUsers();
	} else {
		alert('Text search is not empty');
	}	
}
	





